import { useState, useEffect, useRef } from 'react';
import {
  LoadingOutlined,
} from '@ant-design/icons';

import './Login.less';
import { postJson } from '@/utils/http/linitly.request.js'
import { successPrompt } from '@/utils/default.prompt'

import Image from '@/components/common/Image'
import DefaultCodeImage from '@/assets/code_default.png'

const Login = ({
  history
}) => {

  const usernameRef = useRef()
  const passwordRef = useRef()
  const vertifyCodeRef = useRef()
  const rememberMeRef = useRef()

  const [captcha, setCaptcha] = useState({key: '', vertifyCode: ''})
  const [usernameErrMsg, setUsernameErrMsg] = useState({ error: false, message: '' })
  const [passwordErrMsg, setPasswordErrMsg] = useState({ error: false, message: '' })
  const [vertifyCodeErrMsg, setVertifyCodeErrMsg] = useState({ error: false, message: '' })

  const [ logining, setLogining ] = useState(false)

  const account = getAccount() || {username: '', password: '', check: false}

  useEffect(() => {
    getCaptcha()
  }, []);

  return (
    <div className="login" onKeyUp={keyUpHandle}>
      <div className="login-box">
        <p className="title">Linitly-React-Antd</p>
        <div className="input-line">
          <input type="text" className={`input ${usernameErrMsg.error ? 'error-input' : ''}`} placeholder="请输入用户名"
           ref={usernameRef} defaultValue={account.username} />
          <span className="error-span">&nbsp;{usernameErrMsg.message}</span>
        </div>
        <div className="input-line">
          <input type="password" className={`input ${passwordErrMsg.error ? 'error-input' : ''}`} placeholder="请输入密码"
           ref={passwordRef} defaultValue={account.password} />
          <span className="error-span">&nbsp;{passwordErrMsg.message}</span>
        </div>
        <div className="ver-code">
          <input
            type="text"
            className={`input code-input ${vertifyCodeErrMsg.error ? 'error-input' : ''}`}
            placeholder="请输入验证码"
            ref={vertifyCodeRef}
          />
          <Image src={captcha.vertifyCode} className="code-image" defaultImage={DefaultCodeImage} onClick={getCaptcha} />
          {/* <img src={captcha.vertifyCode} alt="验证码加载失败" className="code-image" onClick={getCaptcha} /> */}
        </div>
        <span className="error-span">&nbsp;{vertifyCodeErrMsg.message}</span>
        <div className="remember-forget">
          <input id="remember" type="checkbox" ref={rememberMeRef} defaultChecked={account.check} />
          <label htmlFor="remember">记住密码</label>
        </div>
        <div className={logining ? 'login-button logining' : 'login-button'}>
          <button onClick={login}>
            <span style={{display: logining ? '' : 'none', marginRight: '10px'}}><LoadingOutlined /></span>
            登&nbsp;录
          </button>
        </div>
      </div>
    </div>
  );

  function login() {
    let username = usernameRef.current.value
    let password = passwordRef.current.value
    let vertifyCode = vertifyCodeRef.current.value
    const successCount = validForm(username, password, vertifyCode)
    if (successCount !== 3) return
    setLogining(true)
    postJson('/login', {
      username,
      password,
      key: captcha.key,
      verCode: vertifyCode
    }).then((res) => {
      successPrompt('登录成功')
      // 将用户信息记录到全局
      sessionStorage.setItem('user', JSON.stringify(res))
      // dispatch(createSetUserAction(res))
      // 是否记住密码
      let rememberMe = rememberMeRef.current.checked
      if (rememberMe) {
        window.localStorage.setItem('account', JSON.stringify({username, password, check: true}))
      } else {
        window.localStorage.removeItem('account')
      }
      setLogining(false)
      // 路由跳转
      history.push('/home')
    }).catch(() => {
      setLogining(false)
    })
  }

  function validForm(username, password, vertifyCode) {
    let successCount = 0
    username ? successCount++ : setUsernameErrMsg({ error: true, message: '请输入用户名' })
    password ? successCount++ : setPasswordErrMsg({ error: true, message: '请输入用户名' })
    if (!vertifyCode) {
      setVertifyCodeErrMsg({ error: true, message: '请输入验证码' })
    } else if (vertifyCode.length !== 4) {
      setVertifyCodeErrMsg({ error: true, message: '验证码位数不正确' })
    } else {
      successCount++
    }
    return successCount
  }

  function getCaptcha() {
    // 获取验证码
    postJson("/captcha").then((res) => {
      setCaptcha({
        key: res.key,
        vertifyCode: res.captchaImage
      })
    });
  }

  // 获取账号信息
  function getAccount() {
    const localAccount = window.localStorage.getItem('account')
    return localAccount ? JSON.parse(localAccount) : ''
  }

  // 监听回车
  function keyUpHandle(e) {
    if(e.keyCode === 13) {
       login()
    }
  }
};

export default Login
